package com.ars.common.servlet.client;

/**
 * ClassName: EditMeServlet
 * Package: com.ars.common.servlet.client
 * Description:
 *
 * @Author: Bryan Long
 * @Create: 2024/9/1 - 10:17
 * @Version: v1.0
 */

import com.ars.common.beans.User.User;
import com.ars.common.dao.UpdateUserInfo;
import com.ars.common.dao.UserInfo.FindUserById;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/editme")
public class EditMeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 在处理请求之前设置字符编码
        request.setCharacterEncoding("UTF-8");
        System.out.println("editme servlet");
        // get origin user info
        String userId = request.getParameter("userID");
        User user = null;
        try {
            user = FindUserById.findUserById(userId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        String gender = request.getParameter("sex");
        System.out.println("gender: " + gender);
        user.setSex(request.getParameter("sex").equals("男") ? "1" : "0");
        user.setMailbox(request.getParameter("mailbox"));
        user.setPhone(request.getParameter("phone"));
        if (request.getParameter("newpwd") != null&&!request.getParameter("newpwd").equals("")) {
            user.setPassword(request.getParameter("newpwd"));
        }

        System.out.println(user.toString());

        UpdateUserInfo updateUserInfo = new UpdateUserInfo();
        try {
            if (updateUserInfo.updateUserInfo(user, user.getUserID())) {
                System.out.println("修改成功");
                String url = request.getContextPath() + "/indexFace/me.jsp";
                response.sendRedirect(url);//跳转
            } else {
                System.out.println("修改失败");
                String url = request.getContextPath() + "/indexFace/editme.jsp";
                response.sendRedirect(url);//跳转
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
}

